
package com.dog.basics.service.common.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.admin.common.AdminDogConnectFlowingFromDto;
import com.dog.basics.bean.dto.admin.common.AdminReportFormAgentDto;
import com.dog.basics.bean.dto.admin.common.AdminReportFormFileldDto;
import com.dog.basics.bean.model.common.DogConnectFlowing;
import com.dog.basics.bean.model.sys.SysUserInfo;
import com.dog.basics.bean.vo.admin.common.AdminDogConnectFlowingHomeVo;
import com.dog.basics.bean.vo.admin.common.AdminDogConnectFlowingInfoVo;
import com.dog.basics.bean.vo.admin.common.AdminDogConnectFlowingVo;
import com.dog.basics.bean.vo.admin.wishwash.AdminReportFormAgentPageVo;
import com.dog.basics.bean.vo.admin.wishwash.AdminReportFormAgentVo;
import com.dog.basics.bean.vo.admin.wishwash.AdminReportFormFileldPageVo;
import com.dog.basics.bean.vo.admin.wishwash.AdminReportFormFileldVo;
import com.dog.basics.common.constant.CommonConstants;
import com.dog.basics.common.util.POIUtil;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.dao.common.DogConnectFlowingMapper;
import com.dog.basics.dao.common.DogUserConnectMapper;
import com.dog.basics.dao.sys.SysUserInfoMapper;
import com.dog.basics.dao.wishwash.DogHxFieldMapper;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.common.DogConnectFlowingService;
import com.dog.basics.service.common.DogUserConnectService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户积分余额流水
 *
 * @author cy code generator
 * @date 2021-04-07 11:23:25
 */
@Service
@AllArgsConstructor
public class DogConnectFlowingServiceImpl extends ServiceImpl<DogConnectFlowingMapper, DogConnectFlowing> implements DogConnectFlowingService {

    private final DogHxFieldMapper fieldMapper;
    private final DogUserConnectService userConnectService;
    private final SysUserInfoMapper userInfoMapper;

    /**
     * @Description: 后台管理分页
     * @Param: status
     * @return: IPage
     * @author cy code generator
     * @date 2021-04-07 11:23:25
     */
    @Override
    public AdminDogConnectFlowingHomeVo getAdminPageList(PageParam page, AdminDogConnectFlowingFromDto obj) {
        // 声明用户标识如果为代理商或者场地则只查询自己的
        if (SecurityUtils.hasRole(CommonConstants.ROLE_AGENT_CODE) || SecurityUtils.hasRole(CommonConstants.ROLE_FIELD_CODE)) {
            // 代理商
            obj.setUserId(SecurityUtils.getSysUser().getUserId());
        }
        // 判断是否有姓名条件
        if (StrUtil.isNotBlank(obj.getUserName())) {
            List<Long> collect = userInfoMapper.selectList(Wrappers.<SysUserInfo>lambdaQuery().select(SysUserInfo::getUserId).like(SysUserInfo::getRealName, obj.getUserName())).stream().map(e -> e.getUserId()).collect(Collectors.toList());
            obj.setUsIds(CollUtil.isNotEmpty(collect) ? collect : CollUtil.newArrayList(CommonConstants.DEFAULT_VAL_LONG));
        }
        // 后台管理 - 分页查询数据信息
        this.page(page, Wrappers.<DogConnectFlowing>lambdaQuery()
                .eq(ObjectUtil.isNotNull(obj.getUserId()), DogConnectFlowing::getUserId, obj.getUserId())
                .in(CollUtil.isNotEmpty(obj.getUsIds()),DogConnectFlowing::getUserId,obj.getUsIds())
                .eq(ObjectUtil.isNotNull(obj.getFromType()), DogConnectFlowing::getFromType, obj.getFromType())
                .between(ObjectUtil.isNotNull(obj.getStartTime()) && ObjectUtil.isNotNull(obj.getEndTime()), DogConnectFlowing::getCreateTime, obj.getStartTime(), obj.getEndTime())
                .orderBy(Boolean.TRUE, obj.getIsOrderByAvg(), DogConnectFlowing::getCreateTime));
        // 格式化数据信息
        List<DogConnectFlowing> records = page.getRecords();
        page.setRecords(records.stream().map(e -> {
            // 数据信息转换
            AdminDogConnectFlowingVo objVo = BeanUtil.toBean(e, AdminDogConnectFlowingVo.class);
            // 下面自定义格式化返回数据
            return objVo;
        }).collect(Collectors.toList()));
        // 数据信息组装
        AdminDogConnectFlowingHomeVo connectFlowingHomeVo = new AdminDogConnectFlowingHomeVo();
        connectFlowingHomeVo.setPage(page);
        // 查询专属余额
        BigDecimal money = userConnectService.getUserMoney(SecurityUtils.getSysUser().getUserId());
        connectFlowingHomeVo.setMybBalance(money);
        // 查询统计金额
        connectFlowingHomeVo.setStatisticalAmount(this.baseMapper.getSumConnectFlowingFrom(obj));
        return connectFlowingHomeVo;
    }


    /**
     * @Description: 后台管理查询详情
     * @Param: obj
     * @return: Boolean
     * @author cy code generator
     * @date 2021-04-07 11:23:25
     */
    @Override
    public AdminDogConnectFlowingInfoVo getAdminObjXq(Long id) {
        // 后台管理 - 查询数据信息是否存在
        DogConnectFlowing obj = this.getById(id);
        // 判断数据是否存在
        Validator.validateNotNull(obj, "common.noData");
        // 数据信息格式化 - 返回
        AdminDogConnectFlowingInfoVo objVo = BeanUtil.toBean(obj, AdminDogConnectFlowingInfoVo.class);
        return objVo;
    }


    /**
     * @Description: 删除
     * @Param: ids
     * @return: Boolean
     * @author cy code generator
     * @date 2021-04-07 11:23:25
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteObj(Long id) {
        // 查询数据信息 - 根据标识
        DogConnectFlowing objInfo = this.getById(id);
        // 判断数据信息是否
        Validator.validateNotNull(objInfo, "common.noData");
        // 执行删除数据信息
        Validator.validateTrue(this.removeById(id), "common.del");
        return Boolean.TRUE;
    }

    /**
     * 代理商受益信息
     *
     * @param param
     * @param dto
     * @return guonh 2021年7月23日
     */
    @Override
    public AdminReportFormAgentVo getAdminReportFormAgent(PageParam param, AdminReportFormAgentDto dto) {
        AdminReportFormAgentVo vo = new AdminReportFormAgentVo();
        dto.setRoleCode(CommonConstants.ROLE_AGENT_CODE);
        // 查询数据信息
        this.baseMapper.getAdminReportFormAgent(param, dto);
        // 格式化数据信息
        List<AdminReportFormAgentPageVo> records = param.getRecords();
        for (int i = 0; i < records.size(); i++) {
            // 查询设备有多少
            Integer devByUserIdAgent = fieldMapper.getCountDevByUserIdAgent(records.get(i).getUserId());
            records.get(i).setDevCount(devByUserIdAgent);
        }
        vo.setPage(param);
        // 全部收益
        if (Validator.equal(param.getCurrent(), BigDecimal.ROUND_DOWN)) {
            vo.setTotalMoney(this.baseMapper.getAdminReportFormAgentSum(dto));
        }
        return vo;
    }

    /**
     * 场地收益信息
     *
     * @param param
     * @param dto
     * @return guonh 2021年7月23日
     */
    @Override
    public AdminReportFormFileldVo getAdminReportFormFileld(PageParam param, AdminReportFormFileldDto dto) {
        AdminReportFormFileldVo vo = new AdminReportFormFileldVo();
        dto.setRoleCode(CommonConstants.ROLE_FIELD_CODE);
        // 查询数据信息
        this.baseMapper.getAdminReportFormFileld(param, dto);
        // 格式化数据信息
        List<AdminReportFormFileldPageVo> records = param.getRecords();
        for (int i = 0; i < records.size(); i++) {
            // 查询设备有多少
            Integer devByUserIdFileld = fieldMapper.getCountDevByUserIdFileld(records.get(i).getUserId());
            records.get(i).setDevCount(devByUserIdFileld);
        }
        vo.setPage(param);
        // 全部收益
        if (Validator.equal(param.getCurrent(), BigDecimal.ROUND_DOWN)) {
            vo.setTotalMoney(this.baseMapper.getAdminReportFormFileldSum(dto));
        }
        return vo;
    }

    /**
     * 导出代理商受益信息
     *
     * @param dto
     * @return guonh 2021年7月23日
     */
    @Override
    public void downloadAdminReportFormAgent(AdminReportFormAgentDto dto) {
        dto.setRoleCode(CommonConstants.ROLE_AGENT_CODE);
        List<AdminReportFormAgentPageVo> adminReportFormAgentList = this.baseMapper.getAdminReportFormAgentList(dto);
        // 统计全部收益
        BigDecimal adminReportFormAgentSum = this.baseMapper.getAdminReportFormAgentSum(dto);
        ExcelWriter writer = ExcelUtil.getBigWriter();
        // 头部
        writer.addHeaderAlias("userId", "User number");
        writer.addHeaderAlias("userName", "What a name");
        writer.addHeaderAlias("money", "Revenue amount");
        writer.addHeaderAlias("devCount", "Number of equipment");
        // 标题
        writer.merge(3, "AgentIncome");
        writer.write(adminReportFormAgentList, Boolean.TRUE);
        // 合并一行
        writer.merge(3, StrUtil.format("Total dividend : {}", adminReportFormAgentSum), Boolean.FALSE);
        POIUtil.createExcel(writer, "AgentIncome");
    }

    /**
     * 导出场地收益信息
     *
     * @param dto
     * @return guonh 2021年7月23日
     */
    @Override
    public void downloadAdminReportFormFileld(AdminReportFormFileldDto dto) {
        dto.setRoleCode(CommonConstants.ROLE_FIELD_CODE);
        List<AdminReportFormFileldPageVo> adminReportFormFileldList = this.baseMapper.getAdminReportFormFileldList(dto);
        // 统计全部收益
        BigDecimal adminReportFormFileldSum = this.baseMapper.getAdminReportFormFileldSum(dto);
        ExcelWriter writer = ExcelUtil.getBigWriter();
        // 头部
        writer.addHeaderAlias("userId", "User number");
        writer.addHeaderAlias("userName", "What a name");
        writer.addHeaderAlias("money", "Revenue amount");
        writer.addHeaderAlias("devCount", "Number of equipment");
        // 标题
        writer.merge(3, "AgentIncome");
        writer.write(adminReportFormFileldList, Boolean.TRUE);
        // 合并一行
        writer.merge(3, StrUtil.format("Total dividend : {}", adminReportFormFileldSum), Boolean.FALSE);
        POIUtil.createExcel(writer, "SiteRevenue");
    }

}
